package com.wx.wxapp.controller.getopenid;

import com.alibaba.fastjson.JSONObject;
import com.wx.wxapp.dao.UserMapper;
import com.wx.wxapp.service.UserSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class getID {
    private final String AppId = "wx4c75818ea1da3d14";
    private final String AppS = "a250355f7b0d4d222cee81d5cb6c368d";
    @Autowired
    private UserSerivce userSerivce;

    //获取用户openID并将用户信息存入数据库中
    @RequestMapping(value = "/getid",method = RequestMethod.GET)
    public String getOpenId(@Param("code") String code, @RequestParam("nickname") String nickname , @RequestParam("image") String image){
        System.out.println(code);
        System.out.println(nickname);

        String grant_type = "authorization_code";
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?";

        String url = requestUrl + "appid=" + AppId + "&secret=" + AppS + "&js_code=" + code + "&grant_type=" + grant_type;
        System.out.println(url);

        String sr = HttpRequest.sendGet(url);
        JSONObject jsonObject = JSONObject.parseObject(sr);
        System.out.println(jsonObject);

        String openid = (String)jsonObject.get("openid");
        System.out.println(openid);

        userSerivce.insertUser(nickname,null,openid,image);

//        String session_key = jsonObject.get("session_key").toString();
//
//        String openid = (String)jsonObject.get("openid");
//        System.out.println(session_key);
//        System.out.println(openid);

        return openid;
    }
}
